package com.example.xpvideo.filter;


import com.example.xpvideo.context.PageContext;
import com.example.xpvideo.tools.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 读取分页信息
 *
 * @author : 洪俊新
 * @date : 2021/3/11 10:48
 * @module
 */
@Component
@WebFilter(urlPatterns = "/**")
public class PageFilter implements Filter {

    /**
     * 获得page参数的值
     *
     * @param request the request
     * @return page num
     */
    protected int getPageNum(HttpServletRequest request) {
        int pageNum = 1;
        try {
            //统一参数
            String pageNums = request.getParameter("page");
            if (StringUtils.isNumeric(pageNums)) {
                pageNum = Integer.parseInt(pageNums);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return pageNum;
    }

    /**
     * 设置默认每页大小
     *
     * @param request the request
     * @return page size
     */
    protected int getPageSize(HttpServletRequest request) {
        // 默认每页10条记录
        int pageSize = 10;
        try {
            //统一参数
            String pageSizes = request.getParameter("size");
            if (StringUtils.isNumeric(pageSizes)) {
                pageSize = Integer.parseInt(pageSizes);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return pageSize;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        PageContext.setPage(getPageNum(httpRequest));
        PageContext.setSize(getPageSize(httpRequest));
        try {
            chain.doFilter(request, response);
        }
        // 使用完Threadlocal，将其删除
        finally {
            PageContext.removePageNum();
            PageContext.removePageSize();
        }
    }

    @Override
    public void destroy() {

    }

}
